<script setup lang="ts">
import { ref } from 'vue';

import {
  BulbOutlined,
  DatabaseOutlined,
  PlayCircleOutlined,
  PlusOutlined,
  TeamOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

const chatModalVisible = ref(false);
const meetingModalVisible = ref(false);
const selectedHeir = ref<any>(null);
const userMessage = ref('');
const meetingTopic = ref('');
const simulationScenario = ref('');
const simulationResults = ref<any[]>([]);

// 表格列定义
const comparisonColumns = [
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '模型', dataIndex: 'modelType', key: 'modelType' },
  { title: '训练度', key: 'trainingLevel' },
  { title: '准确度', key: 'accuracy', width: 150 },
  { title: '状态', key: 'status' },
  { title: '操作', key: 'actions' },
];

// AI Heir列表
const aiHeirs = ref([
  {
    id: 'ai-1',
    name: '朱元璋',
    title: '太祖洪武皇帝',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuYuanzhang',
    modelType: 'GPT-4',
    trainingLevel: 95,
    accuracy: 92,
    isOnline: true,
    trainingDataCount: 15_000,
    conversationCount: 2340,
    modelVersion: 'v2.1.0',
  },
  {
    id: 'ai-2',
    name: '朱棣',
    title: '成祖永乐皇帝',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuDi',
    modelType: 'GPT-4',
    trainingLevel: 88,
    accuracy: 89,
    isOnline: true,
    trainingDataCount: 12_000,
    conversationCount: 1890,
    modelVersion: 'v2.0.5',
  },
  {
    id: 'ai-3',
    name: '朱瞻基',
    title: '宣宗宣德皇帝',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuZhanji',
    modelType: 'GPT-4',
    trainingLevel: 82,
    accuracy: 85,
    isOnline: true,
    trainingDataCount: 8000,
    conversationCount: 1234,
    modelVersion: 'v2.0.0',
  },
  {
    id: 'ai-4',
    name: '朱高炽',
    title: '仁宗洪熙皇帝',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuGaochi',
    modelType: 'GPT-3.5',
    trainingLevel: 75,
    accuracy: 78,
    isOnline: false,
    trainingDataCount: 5000,
    conversationCount: 567,
    modelVersion: 'v1.5.0',
  },
]);

// 聊天历史
const chatHistory = ref<any[]>([
  {
    id: 1,
    role: 'ai',
    content: '朕即朱元璋，有何事请讲？',
    timestamp: new Date().toISOString(),
  },
]);

// 快捷问题
const quickQuestions = ref([
  '如何评价靖难之役？',
  '对当前家族治理有何建议？',
  '如何处理藩国关系？',
  '教育基金如何分配？',
  '如何传承家族文化？',
]);

// 会议讨论
const meetingDiscussion = ref<any[]>([]);

// 会议结果
const meetingResult = ref({
  agree: 0,
  disagree: 0,
  abstain: 0,
  passed: false,
});

function selectHeir(heir: any) {
  selectedHeir.value = heir;
  chatHistory.value = [
    {
      id: 1,
      role: 'ai',
      content: `朕即${heir.name}，有何事请讲？`,
      timestamp: new Date().toISOString(),
    },
  ];
  chatModalVisible.value = true;
}

function sendMessage() {
  if (!userMessage.value.trim()) return;

  // 添加用户消息
  chatHistory.value.push({
    id: Date.now(),
    role: 'user',
    content: userMessage.value,
    timestamp: new Date().toISOString(),
  });

  // 模拟AI回复
  setTimeout(() => {
    const aiResponse = generateAIResponse(
      userMessage.value,
      selectedHeir.value,
    );
    chatHistory.value.push({
      id: Date.now() + 1,
      role: 'ai',
      content: aiResponse,
      timestamp: new Date().toISOString(),
    });
  }, 1000);

  userMessage.value = '';
}

function generateAIResponse(question: string, heir: any): string {
  // Mock AI回答（未来接入真实LLM）
  const responses: Record<string, string> = {
    靖难之役: `朕当年靖难，实乃不得已而为之。建文削藩过急，天下不安，朕起兵护社稷，非为私利。此事虽有争议，但开创永乐盛世，亦可见天命所归。`,
    家族治理: `治家如治国，需刚柔并济。设DAO投票制，集思广益；立SBT身份，明确权责。族长统筹大局，元老建言献策，成员参与决策，如此方能长治久安。`,
    藩国关系: `藩王系皇室宗亲，当以亲情为重，以礼法约束。既要给予封地权力，又要防止尾大不掉。设多签钱包，重大事务需中央批准，即可平衡中央与地方。`,
    教育基金: `教育乃国之根本，家族亦然。建议设立智能合约教育基金，按成绩和贡献自动分配。设最低GPA要求，奖励优异者，如此可激励后辈上进。`,
    文化传承: `文化传承，贵在记录与教育。建数字祠堂，存族谱家训；设家族学堂，授课程故事；用区块链，保永久存证。如此，百年千年，文化不绝。`,
  };

  for (const [key, value] of Object.entries(responses)) {
    if (question.includes(key)) {
      return value;
    }
  }

  return `关于"${question}"，朕以为需从家族长远利益考虑，建议召集元老会议共同商议。此事涉及重大，不可轻率决断。（提示：当前为Mock模式，未来将接入真实AI模型）`;
}

function askQuickQuestion(question: string) {
  userMessage.value = question;
  sendMessage();
}

function createNewHeir() {
  message.info(
    '创建数字孪生功能演示：\n1. 选择家族成员\n2. 收集历史数据\n3. 训练AI模型\n4. 生成数字人格\n（Mock演示，真实功能需Fine-tune GPT-4）',
  );
}

function showVirtualMeeting() {
  meetingModalVisible.value = true;
  meetingDiscussion.value = [];
  meetingResult.value = { agree: 0, disagree: 0, abstain: 0, passed: false };
}

function startMeeting() {
  if (!meetingTopic.value.trim()) {
    message.warning('请输入会议议题');
    return;
  }

  message.loading('AI Heir们正在讨论中...', 2);

  setTimeout(() => {
    // 模拟AI们的发言
    meetingDiscussion.value = [
      {
        id: 1,
        speaker: '朱元璋（AI Heir）',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuYuanzhang',
        content: `关于"${meetingTopic.value}"，朕以为应当慎重考虑，确保家族利益最大化。建议设立专项基金，分阶段实施。`,
        stance: '赞成（条件）',
        color: 'green',
      },
      {
        id: 2,
        speaker: '朱棣（AI Heir）',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuDi',
        content:
          '朕赞同太祖所言，但需增加监督机制。建议引入DAO投票，重大决策需2/3多数通过。',
        stance: '赞成',
        color: 'green',
      },
      {
        id: 3,
        speaker: '朱瞻基（AI Heir）',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuZhanji',
        content:
          '此事确有必要，但需考虑成本与收益。建议先小范围试点，成功后再推广。',
        stance: '赞成（保留意见）',
        color: 'blue',
      },
    ];

    meetingResult.value = {
      agree: 3,
      disagree: 0,
      abstain: 0,
      passed: true,
    };

    message.success('虚拟会议完成！AI Heir们已形成共识。');
  }, 2000);
}

function formatTime(timestamp: string) {
  return dayjs(timestamp).format('HH:mm:ss');
}

function viewTrainingData(heir: any) {
  message.info(
    `${heir.name} AI Heir训练数据：\n✓ 历史文献：${Math.floor(heir.trainingDataCount * 0.4)}条\n✓ 决策记录：${Math.floor(heir.trainingDataCount * 0.3)}条\n✓ 家族对话：${Math.floor(heir.trainingDataCount * 0.2)}条\n✓ 历史事件：${Math.floor(heir.trainingDataCount * 0.1)}条`,
  );
}

function viewPersonality(heir: any) {
  message.info(
    `${heir.name} AI人格分析：\n✓ 决策风格：果断型\n✓ 沟通方式：权威式\n✓ 核心价值：家族利益优先\n✓ 历史特征：开创性、战略性\n✓ 语言特点：文言为主，庄重威严`,
  );
}

function simulateDecision(heir: any) {
  simulationScenario.value = `假设${heir.name}面临：是否支持家族教育基金提案`;
  runSimulation();
}

function runSimulation() {
  if (!simulationScenario.value.trim()) {
    message.warning('请输入模拟场景');
    return;
  }

  message.loading('AI们正在基于历史数据模拟决策...', 2);

  setTimeout(() => {
    simulationResults.value = aiHeirs.value.slice(0, 3).map((heir) => ({
      name: heir.name,
      avatar: heir.avatar,
      decision:
        heir.name === '朱元璋'
          ? '赞成，但需设立严格审核机制'
          : heir.name === '朱棣'
            ? '强烈赞成，教育乃国之根本'
            : '赞成，建议增加奖励激励',
      reasoning: `基于${heir.name}历史决策模式和价值观分析`,
      historicalMatch: `与${heir.name}在${Math.floor(Math.random() * 20 + 1400)}年的类似决策相似度${Math.floor(Math.random() * 10 + 85)}%`,
      confidence: Math.floor(Math.random() * 10 + 85),
    }));

    message.success('决策模拟完成！');
  }, 2000);
}
</script>

<template>
  <div class="ai-heir-page">
    <a-card>
      <template #title>
        <div class="page-header">
          <span>🤖 AI Heir - 数字孪生体</span>
          <a-space>
            <a-button type="primary" @click="createNewHeir">
              <PlusOutlined /> 创建数字孪生
            </a-button>
            <a-button @click="showVirtualMeeting">
              <TeamOutlined /> 召开虚拟会议
            </a-button>
          </a-space>
        </div>
      </template>

      <!-- AI Heir列表 -->
      <a-row :gutter="16">
        <a-col v-for="heir in aiHeirs" :key="heir.id" :span="6">
          <a-card hoverable class="heir-card">
            <div class="heir-avatar" @click="selectHeir(heir)">
              <a-avatar :src="heir.avatar" :size="80" />
              <a-badge
                :count="heir.isOnline ? '在线' : '离线'"
                :color="heir.isOnline ? 'green' : 'gray'"
              />
            </div>
            <h3 @click="selectHeir(heir)">{{ heir.name }}</h3>
            <p class="heir-title">{{ heir.title }}</p>
            <a-space direction="vertical" style="width: 100%">
              <a-tag color="blue">AI模型：{{ heir.modelType }}</a-tag>
              <a-tag color="purple">训练度：{{ heir.trainingLevel }}%</a-tag>
              <a-progress :percent="heir.accuracy" size="small" />
            </a-space>
            <a-space style="width: 100%; margin-top: 12px">
              <a-button size="small" block @click="viewTrainingData(heir)">
                <DatabaseOutlined /> 训练数据
              </a-button>
              <a-button size="small" block @click="viewPersonality(heir)">
                <BulbOutlined /> 人格分析
              </a-button>
            </a-space>
          </a-card>
        </a-col>
      </a-row>

      <!-- AI能力统计 -->
      <a-card title="📊 AI Heir 能力对比" style="margin-top: 16px">
        <a-table
          :data-source="aiHeirs"
          :columns="comparisonColumns"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'accuracy'">
              <a-progress
                :percent="record.accuracy"
                size="small"
                :stroke-color="record.accuracy > 90 ? '#52c41a' : '#1890ff'"
              />
            </template>
            <template v-if="column.key === 'trainingLevel'">
              {{ record.trainingLevel }}%
            </template>
            <template v-if="column.key === 'status'">
              <a-tag :color="record.isOnline ? 'green' : 'gray'">
                {{ record.isOnline ? '在线' : '离线' }}
              </a-tag>
            </template>
            <template v-if="column.key === 'actions'">
              <a-space>
                <a @click="selectHeir(record)">对话</a>
                <a @click="simulateDecision(record)">决策模拟</a>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>

      <!-- 决策模拟 -->
      <a-card title="🎯 历史决策模拟" style="margin-top: 16px">
        <a-form layout="inline">
          <a-form-item label="场景">
            <a-input
              v-model:value="simulationScenario"
              placeholder="输入历史场景..."
              style="width: 400px"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="runSimulation">
              <PlayCircleOutlined /> 开始模拟
            </a-button>
          </a-form-item>
        </a-form>

        <a-card
          v-if="simulationResults.length > 0"
          title="模拟结果"
          size="small"
          style="margin-top: 16px"
        >
          <a-list :data-source="simulationResults">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :src="item.avatar" />
                  </template>
                  <template #title>{{ item.name }}的决策</template>
                  <template #description>
                    <div><strong>决策：</strong>{{ item.decision }}</div>
                    <div><strong>理由：</strong>{{ item.reasoning }}</div>
                    <div>
                      <strong>历史对比：</strong>{{ item.historicalMatch }}
                    </div>
                  </template>
                </a-list-item-meta>
                <a-tag color="blue">可信度：{{ item.confidence }}%</a-tag>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-card>
    </a-card>

    <!-- AI Heir对话面板 -->
    <a-modal
      v-model:open="chatModalVisible"
      :title="`💬 与${selectedHeir?.name}的AI Heir对话`"
      width="1000px"
      :footer="null"
    >
      <a-row :gutter="16">
        <a-col :span="16">
          <div class="chat-container">
            <div class="messages">
              <div
                v-for="msg in chatHistory"
                :key="msg.id"
                class="message"
                :class="[msg.role]"
              >
                <a-avatar
                  v-if="msg.role === 'ai'"
                  :src="selectedHeir?.avatar"
                />
                <div class="message-content">
                  <div class="message-header">
                    <strong>{{
                      msg.role === 'user' ? '您' : selectedHeir?.name
                    }}</strong>
                    <span class="time">{{ formatTime(msg.timestamp) }}</span>
                  </div>
                  <div class="message-text">{{ msg.content }}</div>
                </div>
              </div>
            </div>
            <div class="chat-input">
              <a-input-search
                v-model:value="userMessage"
                placeholder="向AI Heir提问..."
                enter-button="发送"
                size="large"
                @search="sendMessage"
              />
            </div>
          </div>
        </a-col>
        <a-col :span="8">
          <a-card title="💡 快捷提问" size="small">
            <a-space direction="vertical" style="width: 100%">
              <a-button
                v-for="q in quickQuestions"
                :key="q"
                block
                size="small"
                @click="askQuickQuestion(q)"
              >
                {{ q }}
              </a-button>
            </a-space>
          </a-card>

          <a-card title="📊 AI能力" size="small" style="margin-top: 16px">
            <a-descriptions :column="1" size="small">
              <a-descriptions-item label="决策准确度">
                {{ selectedHeir?.accuracy }}%
              </a-descriptions-item>
              <a-descriptions-item label="训练数据量">
                {{ selectedHeir?.trainingDataCount }} 条
              </a-descriptions-item>
              <a-descriptions-item label="对话次数">
                {{ selectedHeir?.conversationCount }} 次
              </a-descriptions-item>
              <a-descriptions-item label="模型版本">
                {{ selectedHeir?.modelVersion }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
      </a-row>
    </a-modal>

    <!-- 虚拟会议Modal -->
    <a-modal
      v-model:open="meetingModalVisible"
      title="🏛️ 虚拟家族会议"
      width="1200px"
      :footer="null"
    >
      <a-card title="会议议题" size="small">
        <a-input v-model:value="meetingTopic" placeholder="输入会议议题..." />
        <a-button type="primary" style="margin-top: 12px" @click="startMeeting">
          开始会议
        </a-button>
      </a-card>

      <a-card title="💬 会议讨论" style="margin-top: 16px">
        <a-timeline>
          <a-timeline-item
            v-for="discussion in meetingDiscussion"
            :key="discussion.id"
            :color="discussion.color"
          >
            <template #dot>
              <a-avatar :src="discussion.avatar" :size="32" />
            </template>
            <div class="discussion-item">
              <strong>{{ discussion.speaker }}</strong>
              <p>{{ discussion.content }}</p>
              <a-tag>{{ discussion.stance }}</a-tag>
            </div>
          </a-timeline-item>
        </a-timeline>
      </a-card>

      <a-card title="📊 会议总结" style="margin-top: 16px">
        <a-descriptions bordered :column="2">
          <a-descriptions-item label="赞成">
            {{ meetingResult.agree }}人
          </a-descriptions-item>
          <a-descriptions-item label="反对">
            {{ meetingResult.disagree }}人
          </a-descriptions-item>
          <a-descriptions-item label="弃权">
            {{ meetingResult.abstain }}人
          </a-descriptions-item>
          <a-descriptions-item label="结果">
            <a-tag :color="meetingResult.passed ? 'green' : 'red'">
              {{ meetingResult.passed ? '✓ 通过' : '✗ 未通过' }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.ai-heir-page {
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .heir-card {
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 4px 20px rgb(24 144 255 / 30%);
      transform: translateY(-4px);
    }

    .heir-avatar {
      position: relative;
      margin-bottom: 16px;

      :deep(.ant-badge) {
        position: absolute;
        top: 0;
        right: calc(50% - 50px);
      }
    }

    h3 {
      margin: 8px 0;
      font-size: 16px;
    }

    .heir-title {
      margin-bottom: 12px;
      font-size: 13px;
      color: #666;
    }
  }

  .chat-container {
    display: flex;
    flex-direction: column;
    height: 500px;

    .messages {
      flex: 1;
      padding: 16px;
      margin-bottom: 16px;
      overflow-y: auto;
      background: #f5f5f5;
      border-radius: 4px;

      .message {
        display: flex;
        gap: 12px;
        margin-bottom: 16px;

        &.user {
          flex-direction: row-reverse;

          .message-content {
            color: white;
            background: #1890ff;
          }
        }

        .message-content {
          max-width: 70%;
          padding: 12px;
          background: white;
          border-radius: 8px;
          box-shadow: 0 2px 8px rgb(0 0 0 / 10%);

          .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 12px;

            .time {
              color: #999;
            }
          }

          .message-text {
            line-height: 1.6;
          }
        }
      }
    }

    .chat-input {
      margin-top: auto;
    }
  }

  .discussion-item {
    strong {
      color: #1890ff;
    }

    p {
      margin: 8px 0;
      line-height: 1.6;
    }
  }
}
</style>
